/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import org.latestbit.smartobjects.exceptions.HandshakeException;
import org.latestbit.smartobjects.exceptions.IncorrectURIException;
import org.latestbit.smartobjects.network.*;


public class TCPConnector extends TCPConnection implements IConnector {
	private SelectionKey connectorChannelKey = null;
	private SocketMultiplexer connectorMultiplexer;
	private final String CONNECTOR_MULTIPLEXER_GROUP_NAME = "CONNECTORS";
	
	public TCPConnector(TCPSharedResources resources) throws IOException {
		super(resources);
		this.connectorMultiplexer 
			= resources.getSocketMultiplexer(CONNECTOR_MULTIPLEXER_GROUP_NAME);				
	}

	private void createSocketChannel() throws IOException {
		setChannel(SocketChannel.open());
	}

	@Override
	public void connect() throws IncorrectURIException, IOException {
		channelLock.lock();
		try {
			close();
			
			createSocketChannel();
			getChannel().configureBlocking(true);
			URI toConnectURI = getEndpointURI();
			getChannel().connect( 
					new InetSocketAddress( toConnectURI.getHost(), toConnectURI.getPort()) 
			);
			start();
		}
		finally {
			channelLock.unlock();
		}			
	}

	@Override
	public void connectAsync() throws IncorrectURIException, IOException {
		channelLock.lock();
		try {		
			close();
			createSocketChannel();
			getChannel().configureBlocking(false);
	        URI toConnectURI = getEndpointURI();
	        
	        connectorChannelKey = connectorMultiplexer.addChannel(
	    			getChannel(), 
	    			SelectionKey.OP_CONNECT, 
	    			this
	    	);        
	        
	        this.getChannel().connect(new InetSocketAddress( toConnectURI.getHost(), toConnectURI.getPort()));
		}
		finally {
			channelLock.unlock();
		}
	}


	@Override
	public void close() {
		channelLock.lock();
		try {				
			if(connectorChannelKey!=null && connectorChannelKey.isValid()) {
				connectorMultiplexer.removeChannel(connectorChannelKey);
			}
			super.close();
		}
		finally {
			channelLock.unlock();
		}			
	}

	@Override
	public void onSelectedEvent(SelectionKey selectionKey) {
		boolean isConnectable = false;
		channelLock.lock();
		try {
			isConnectable = selectionKey.isValid() && selectionKey.isConnectable();
		}
		finally {
			channelLock.unlock();
		}
		if(isConnectable) {
			try {
				channelLock.lock();
				try {
					SocketChannel channel = getChannel();
					if(channel!=null)
						channel.finishConnect();
					else
						throw new IOException("Channel is closed");
					connectorMultiplexer.removeChannel(selectionKey);
				}
				finally {
					channelLock.unlock();
				}

				if(this.handshakeManager==null) {
					// If there is no handshake procedure
					fireOnConnected();
				}
				else {
					try { 
						getHandshakeManager().beginHandshake( );
					}
					catch(HandshakeException ex) {
						throw new IOException ( ex.toString() );
					}
				}				
				
				start();
			} 
			catch (IOException e) {
				fireOnConnectionFailure(e.toString());
			}			
		}
		else
			super.onSelectedEvent(selectionKey);
	}
	
	@Override
	protected void fireOnConnected() {
		synchronized (connectionListeners) {
			palConnectionListeners.activate();
			try {
				for(IConnectionListener listener : connectionListeners) {
					listener.onConnected(this);
				}
			}
			finally {
				processingPostActionConnectionListeners();
			}
		}
	}
		
	
	protected void fireOnConnectionFailure(String errorMessage) {
		synchronized (connectionListeners) {
			palConnectionListeners.activate();
			try {
				for(IConnectionListener listener : connectionListeners) {
					listener.onConnectionFailure(this, errorMessage);
				}
			}
			finally {
				processingPostActionConnectionListeners();
			}
		}
	}	

	@Override
	public boolean isAcceptorConnection() {
		return false;
	}	

}
